package controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@ManagedBean
@ViewScoped
public class FileDownloadBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private StreamedContent file;
	private String contentTypeString;
	private String materia;

	public FileDownloadBean() throws FileNotFoundException {
		String nome = FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterMap().get("nome");
		setMateria((String) FacesContext.getCurrentInstance()
				.getExternalContext().getApplicationMap().get("materia"));

		FacesContext fc = FacesContext.getCurrentInstance();
		ServletContext sc = (ServletContext) fc.getExternalContext()
				.getContext();
		String path = sc.getRealPath(File.separator + "arquivos" + File.separator
				+ materia + File.separator + nome);
		setContentTypeString(FacesContext.getCurrentInstance().getExternalContext()
				.getMimeType(path));

		InputStream stream = new FileInputStream(path);
		file = new DefaultStreamedContent(stream, getContentTypeString(),nome);
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public void setContentTypeString(String contentTypeString) {
		this.contentTypeString = contentTypeString;
	}

	public String getContentTypeString() {
		return contentTypeString;
	}

	public void setMateria(String materia) {
		this.materia = materia;
	}

	public String getMateria() {
		return materia;
	}

}
